package com.hpeu_01.day0126;

import org.junit.Test;

import java.lang.reflect.Constructor;

public class ReflectByConstructor {
    /**
     * getDeclaredConstructor(Class<?>... parameterTypes)：用于获取指定类型的构造器
     * getDeclaredConstructors()：获取所有构造器（本类）
     * getConstructors()：获取所有构造器，包括父类的构造器
     *
     * @throws Exception
     */

    @Test
    public void test04() throws Exception {
        ClassLoader classLoader = this.getClass().getClassLoader();
        Class<?> aClass = classLoader.loadClass("com.hpeu_01.day0126.Person");
        //clazz.getDeclaredConstructors()：获取本类中所有的构造器，括私有
        Constructor<?>[] constructors = aClass.getDeclaredConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }
    }

    @Test
    public void test03(){
        Person person = new Person();
        Class<? extends Person> clazz = person.getClass();
        //clazz.getConstructors()：获取所有被public修饰构造器
        Constructor<?>[] constructors = clazz.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }
    }

    @Test
    public void test02() throws Exception {
        Class<?> aClass = Class.forName("com.hpeu_01.day0126.Person");
        //getDeclaredConstructor(Class<?>... parameterTypes)：用于获取指定类型的构造器
        Constructor<?> constructor = aClass.getDeclaredConstructor(Integer.class, String.class);
        String name = constructor.getDeclaringClass().getSimpleName();
        System.out.println(name);

        Object newInstance = constructor.newInstance(1, "张三");
        System.out.println(newInstance);
    }
    @Test
    public void test01() throws IllegalAccessException, InstantiationException {
        Class<Person> clazz = Person.class;
        // 调用无参构造来实例化对象
        Person person = clazz.newInstance();
        System.out.println(person);
    }
}
